#if Facebook
using Facebook.Unity;
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using System.Text;
#if GooglePlay
using Google.Play.Review;
#endif
using UnityEngine;
using UnityEngine.UI;


public interface UISettingListener
{
	void OnMusicToggle(bool isOn);
	void OnSoundToggle(bool isOn);
	void OnVibrationToggle(bool isOn);
	void OnLanguageType(int type);
	void OnTestMode(bool isOn);
}
[System.Serializable]
public class SettingPanelData
{
	public bool musicOn;
	public bool soundOn;
	public bool vibrationOn;
	public bool TestingMode;
	public LanguageType languageType;
}


public class SettingPanel:PanelCommon
{
	public Text gameIdText;
	public Text settingNoticeText;
	public SettingPanelToggle musicPanelToggle;
	public SettingPanelToggle soundPanelToggle;
	public SettingPanelToggle vibrationToggle;
	
	public ListTogglesGroup languageTogglesGroup;

	public GameObject bingingBtn;
	public GameObject reviewBtn;
	public GameObject shareRewardGo;
	public Text shareRewardText;
	
	SettingPanelData m_SettingPanelData;

	public UISettingListener uiSettingListener;

	private static string settingNotice = "";

	public const string settingNoticeUrl = "";
	
	public override void Start()
	{
		base.Start();

		UIFit();

		if(musicPanelToggle)
			musicPanelToggle.onToggleValue = this.OnMusicToggle;
		
		if(soundPanelToggle)
			soundPanelToggle.onToggleValue = this.OnSoundToggle;

		if(vibrationToggle)
			vibrationToggle.onToggleValue = this.OnVibrationToggle;
		
		if (settingNoticeText)
			settingNoticeText.text = Localization.instance.GetValue("");

#if Facebook
		shareRewardGo.transform.parent.parent.gameObject.SetActive(true);

		shareRewardGo.SetActive(GameCtrl.Instance.user.obtainShareReward <= 0);
		shareRewardText.text = ConstData.Instance.battleRules.shareGetDiamond.ToString();
		StartCoroutine(AdjustLayout(shareRewardGo.transform.parent.GetComponentInChildren<LayoutGroup>()));

		 if (!s_ShowedShareGuide)
        {
			s_ShowedShareGuide = true;
			DoActionDelay.DelayAction(0.2f, () =>
			{
				GameCtrl.Instance.guidanceController.ShowGuide(0.12f, this.shareRewardGo.transform.parent.parent.GetComponentInChildren<Image>(),string.Format(Localization.instance.GetValue("guide_03"),ConstData.Instance.battleRules.shareGetDiamond),null,1);
			});
		}
#else
		if(shareRewardGo)
			shareRewardGo.transform.parent.parent.gameObject.SetActive(false);
#endif
       
	}
	
	const string ShareGuideKey = "ShareGuide";
	static bool s_ShowedShareGuide
    {
        get
        {
			return PlayerPrefs.GetInt(ShareGuideKey) > 0;
        }
        set
        {
			PlayerPrefs.SetInt(ShareGuideKey, value ? 1 : 0);

		}
    }

	protected override void OnShowAnimEnd()
	{
		base.OnShowAnimEnd();
	}


	void UIFit()
	{
		/*if (DeviceInfo.isiPhoneX)
			top = 120;
		else if (DeviceInfo.isIpad)
			top = 140;*/
	}
	public void Init(SettingPanelData panelData)
	{
		m_SettingPanelData = panelData;

		if (musicPanelToggle)
		{
			musicPanelToggle.isOn = panelData.musicOn;
			musicPanelToggle.OnToggleValueChange(musicPanelToggle.isOn);
		}

		if (soundPanelToggle)
		{
			soundPanelToggle.isOn = panelData.soundOn;
			soundPanelToggle.OnToggleValueChange(soundPanelToggle.isOn);
		}
		if (vibrationToggle)
		{
			vibrationToggle.isOn = panelData.soundOn;
			vibrationToggle.OnToggleValueChange(vibrationToggle.isOn);
		}
			
		if(languageTogglesGroup)
			languageTogglesGroup.Init(OnLanguageSelect, (int) panelData.languageType);
	}


	public void OnMusicToggle(bool isOn)
	{
		GameDebug.LogError("music toggle"); 
		
		if (this.uiSettingListener == null)
			uiSettingListener = this.GetComponentInParent<GameSettingViewController>();

		uiSettingListener.OnMusicToggle(isOn);
	}

	public void OnSoundToggle(bool isOn)
	{
		if (this.uiSettingListener == null)
			uiSettingListener = this.GetComponentInParent<GameSettingViewController>();

		uiSettingListener.OnSoundToggle(isOn);
	}
	public void OnVibrationToggle(bool isOn)
	{
		if (this.uiSettingListener == null)
			uiSettingListener = this.GetComponentInParent<GameSettingViewController>();

		uiSettingListener.OnVibrationToggle(isOn);
	}
	public void OnTestingModeToggle(bool isOn)
	{		
		if (this.uiSettingListener == null)
			uiSettingListener = this.GetComponentInParent<GameSettingViewController>();
		uiSettingListener.OnTestMode(isOn);
	}

	
	void OnLanguageSelect(int type)
	{
		GameDebug.Log("OnLanguageSelect:" + m_SettingPanelData.languageType);

		if (this.uiSettingListener != null)
			uiSettingListener.OnLanguageType(type);
	}

	public void OnClickReview()
	{
		ShowReview(this);
	}

	public static void ShowReview(MonoBehaviour obj)
	{
#if GooglePlay
			obj.StartCoroutine(IE_GooglePlayReview());
#else
		if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.OSXEditor)
		{
			const string APP_ID = "1523197698";
			var url = string.Format("itms-apps://itunes.apple.com/cn/app/id{0}?mt=8&action=write-review",APP_ID);
			Application.OpenURL(url);
		}
#endif
	}
	
	static IEnumerator IE_GooglePlayReview () 
	{
		GameDebug.Log("open review begin !");

#if GooglePlay
        ReviewManager rm = new ReviewManager();
        var requestFlowOperation = rm.RequestReviewFlow();
        yield return requestFlowOperation;
        if (requestFlowOperation.Error != ReviewErrorCode.NoError)
        {
            Debug.LogFormat("requestFlowOperation:{0}", requestFlowOperation.Error);
			Application.OpenURL("https://play.google.com/store/apps/details?id=com.zhan.petsfight");
            yield break;
        }
        PlayReviewInfo playReviewInfo = requestFlowOperation.GetResult();
        var launchFlowOperation = rm.LaunchReviewFlow(playReviewInfo);
        yield return launchFlowOperation;
        playReviewInfo = null; // Reset the object
        if (launchFlowOperation.Error != ReviewErrorCode.NoError)
        {
			GameDebug.LogError("Error:" + requestFlowOperation.Error.ToString());
			Application.OpenURL("https://play.google.com/store/apps/details?id=com.zhan.petsfight");
            yield break;
        }
#else
	Application.OpenURL("https://play.google.com/store/apps/details?id=com.zhan.petsfight");
#endif

		yield return 0;
		GameDebug.Log("open review over !");
	}

	public void OnClickShare()
	{
		GameDebug.Log("OnClickShare !");
#if Facebook
		Uri contentURL = null;
#if UNITY_ANDROID
        contentURL = new Uri("https://play.google.com/store/apps/details?id=com.zhan.petsfight");
#elif UNITY_IOS
		 contentURL = new Uri("https://apps.apple.com/app/id1523197698");
#endif
		FB.ShareLink(contentURL, "Pets Fight", "Let's play a fun game!",  null, ShareCallback);
#endif
	}

#if Facebook
	private void ShareCallback(IShareResult result)
	{
		if (result.Cancelled || !String.IsNullOrEmpty(result.Error))
		{
			Debug.Log("ShareLink Error: " + result.Error);
		}
		else
		{
			if (!String.IsNullOrEmpty(result.PostId))
			{
				// Print post identifier of the shared content
				Debug.Log("ShareLink  PostId:" + result.PostId);
			}
			else
			{
				// Share succeeded without postID
				Debug.Log("ShareLink success!");
			}
			if (GameCtrl.Instance.user.obtainShareReward == 0)
			{
				NumsShowController.delayUpdateNumShow = true;

				Request_ShareSuc requestBase = new Request_ShareSuc();

				requestBase.intData = new IntData();
				requestBase.intData.value = 1;

				requestBase.clientSocket = GameCtrl.Instance.clientSocket;

				requestBase.onResponse = (res) =>
				{
					GameDebug.Log("�@�ê���");
					GameCtrl.Instance.user.obtainShareReward = 1;
					this.shareRewardGo.SetActive(false);
					HomePanelViewContrller.CheckUpdateDiamond(this.shareRewardGo.transform.position,transform);

					//GameCtrl.Instance.ShowNoticePanel(string.Format(Localization.instance.GetValue("get_diamond"),ConstData.Instance.battleRules.shareGetDiamond));
				};
				requestBase.onTimeOut = (req) => { GameCtrl.Instance.ShowNoticePanel(Localization.instance.GetValue("request_timed_out")); };

				requestBase.Send();
			}
		}
	}
#endif
	public void OnClickFacebookWebsite()
	{
		Application.OpenURL("https://www.facebook.com/Pets-Fight-104058178181491");

	}
	public void OnClickWebsite()
	{
		GameDebug.Log("OnClickWebsite !");

		Application.OpenURL("http://zhanhailong.net");

	}

    protected override void GoBackToView()
    {
		this.m_Controller.parentNav.LoadDisplay<MBattleUIViewController>();
    }
}